package com.quan.service;

import com.quan.Enum.CommonByteEnum;
import com.quan.Enum.ResultEnum;
import com.quan.dao.CommodityImageRepository;
import com.quan.entity.CommodityImage;
import com.quan.exception.GlobalException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.HashSet;
import java.util.Set;

/**
 * @author: xiexinquan520@163.com
 * User: XieXinQuan
 * DATE:2020/5/19
 */
@Service
public class FileService {
    @Resource
    CommodityImageRepository commodityImageRepository;
    @Value("${server.port}")
    Integer serverPort;

    public String save(Long commodityId, MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            throw new GlobalException(ResultEnum.ParameterError.getKey(), "请添加至少一张图片.");
        }
        //保存图片
        String fileUrl = this.save(file);
        CommodityImage image = new CommodityImage();
        image.setCommodityId(commodityId);
        image.setFileName(fileUrl.substring(fileUrl.lastIndexOf('/')+1));
        image.setSize(image.getSize());
        image.setImageUrl(fileUrl);
        image.setStatus(CommonByteEnum.Normal.getKey());
        commodityImageRepository.save(image);
        return fileUrl;
    }

    public String save(MultipartFile webFile) throws IOException {
        //获取项目路径
        String userDirPath = System.getProperty("user.dir");

        userDirPath += File.separator + "webimages";
        String originalFilename = webFile.getOriginalFilename();
        File toFile = new File(userDirPath);
        if (!toFile.exists()){
            toFile.mkdir();
        }
        File[] files = toFile.listFiles();
        Set<String> allFileName = new HashSet<>(files.length);
        for (File file : files){
            allFileName.add(file.getName());
        }
        String fileName = webFile.getOriginalFilename();
        while (allFileName.contains(fileName)){
            fileName = fileName.substring(0, fileName.lastIndexOf(".")) + (int)(Math.random() * 10) + fileName.substring(fileName.lastIndexOf("."));
        }
        toFile = new File(userDirPath + File.separator + fileName);

        webFile.transferTo(toFile);

        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        return String.format("http://%s:%d/webimages/%s", hostAddress, serverPort, fileName);
    }

}
